<!-- 品牌管理 -->
<template>
  <div class="brand sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="品牌名称:">
              <el-input v-model="query.name" placeholder="请输入品牌名称" clearable/>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Plus" color="#FFB800" @click="toAdd">新增</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="品牌数据" icon="CollectionTag" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中" >
        <el-table ref="table" :data="dataList" max-height="493" border>
          <el-table-column label="编号" type="index" align="center" width="80"></el-table-column>
          <el-table-column label="品牌名称" prop="name" align="center"></el-table-column>
          <el-table-column label="logo" prop="logo" align="center">
            <template #default="{row}">
              <div class="img-cell">
                <el-image :src="row.logo + '?x-oss-process=image/resize,m_fill,h_40,w_40'"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="厂商名称" prop="merchantName" align="center"></el-table-column>
          <el-table-column label="首字母" prop="firstLetter" align="center"></el-table-column>
          <el-table-column label="启用状态" prop="enableStatus" align="center">
            <template #default="{row}">
              <el-tag :type="row.enableStatus ? 'success' : 'danger'">{{ row.enableStatus ? '已启用' : '已禁用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="240">
            <template #default="{row}">
              <el-button type="primary" icon="Edit" link @click="toUpdate(row.brandId)">修改</el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" icon="Delete" link @click="doDelete(row.brandId)">删除</el-button>
              <el-divider direction="vertical" />
              <el-button 
                :type="row.enableStatus ? 'danger' : 'success'" 
                :icon="row.enableStatus ? 'WarnTriangleFilled' : 'SuccessFilled'" 
                link 
                @click="doUpdateStatus(row)">
                {{row.enableStatus ? '禁用' : '启用'}}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 新增、编辑弹窗 -->
    <el-dialog v-model="show" :title="form.brandId ? '编辑' : '新增'" top="10vh" width="55%" :destroy-on-close="true" center draggable @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" size="default" label-width="85px">
        <el-form-item label="品牌名称:" prop="name" required>
          <el-input v-model="form.name" placeholder="请输入品牌名称" clearable/>
        </el-form-item>
        <el-form-item label="首字母:" prop="firstLetter">
          <el-input v-model="form.firstLetter" maxlength="1" placeholder="请输入标题" clearable/>
        </el-form-item>
        <el-form-item label="排序:" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="商品logo:" prop="logo" required>
          <img-cutter v-model="form.logo" :isCard="true" :multiple="false" width="60" height="60"></img-cutter>
        </el-form-item>
        <el-form-item label="品牌大图:" prop="bigPic">
          <img-cutter v-model="form.bigPic" :isCard="true" :multiple="false" width="300" height="180"></img-cutter>
        </el-form-item>
        <el-form-item label="品牌故事:" prop="brandStory">
          <tinymce-editor v-model="form.brandStory" ref="editorRef"></tinymce-editor>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="doSubmit">保存</el-button>
        <el-button size="default" @click="show = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="brand">
  import { cudBrandApi, getBrandListPagesApi, getBrandInfoApi, updateBrandStatusApi } from '@/api/api'
  import { ref, reactive, toRefs, getCurrentInstance, onActivated } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  const formRef = ref(null)
  const editorRef = ref(null)

  const currentData = reactive({
    loading: false,
    show: false,
    query: {
      name: '',
      current: 1,
      size: 20,
      total: 0
    },
    dataList: [],
    form: {
      brandId: '',
      name: '',
      firstLetter: '',
      orderNum: 1,
      logo: '',
      bigPic: '',
      brandStory: '',
      enableStatus: 1
    },
    rules: {
      name: [{ required: true, message: '请输入品牌名称', trigger: ['blur', 'change'] }],
      logo: [{ required: true, message: '请上传商品logo', trigger: ['blur', 'change'] }]
    }
  })
  let {loading, show, query, dataList, form, rules} = toRefs(currentData)

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getBrandListPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 新增或编辑
  function doSubmit() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm(`确认${currentData.form.brandId ? '修改' : '新增'}吗？`).then(() => {
          let loading = currentThis.$loading(`正在${currentData.form.brandId ? '修改' : '新增'}`)
          cudBrandApi(`${currentData.form.brandId ? 'update' : 'save'}`, currentData.form).then(res => {
            loading.close()
            if(res.code === '200') {
              currentThis.$message.success(res.message)
              currentData.show = false
              load(currentData.form.brandId ? currentData.query.current : 1)
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  function toAdd() {
    currentData.form.brandStory = ''
    currentData.show  = true
  }

  // 修改前弹窗
  function toUpdate(brandId) {
    getBrandInfoApi(brandId).then(res => {
      if(res.code === '200') {
        currentData.form = res.data
        currentData.show = true
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 删除
  function doDelete(brandId) {
    currentThis.$messageBox.confirm('确认删除吗？').then(() => {
      let loading = currentThis.$loading('正在删除，请耐心等待')
      cudBrandApi('delete', { id: brandId }).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 启用或禁用
  function doUpdateStatus(e) {
    currentThis.$messageBox.confirm(`确认${e.enableStatus ? '禁用' : '启用'}吗？`).then(() => {
      let loading = currentThis.$loading('正在处理，请耐心等待')
      updateBrandStatusApi(e.brandId, e.enableStatus ? 0 : 1).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 重置查询
  function resetSearch() {
    currentData.query.name = ''
    load(1)
  }

  function resetForm() {
    currentData.form = {
      brandId: '',
      name: '',
      firstLetter: '',
      orderNum: 1,
      logo: '',
      bigPic: '',
      brandStory: '',
      enableStatus: 1
    }
    formRef.value.resetFields()
    editorRef.value.destroyEditor()
  }

  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }

  onActivated(() => {
    load(currentData.query.current)
  })
</script>

<style lang="less" scoped>
.brand{
  :deep(.el-select.custom_select){
    .el-input{
      width: 200px !important;
    }
  }
  :deep(.el-table){
    .img-cell{
      display: flex;
      justify-content: center;
      align-items: center;
      .el-image{
        width: 40px; 
        height: 40px;
        border-radius: 5px;
      }
    }
  }
  :deep(.el-dialog){
    .el-dialog__body{
      max-height: 600px;
      overflow: hidden auto;
    }
    .el-input, .el-textarea{
      width: 300px;
    }
    .el-select{
      .el-input{
        width: 300px !important;
      }
    }
  }
}
</style>